#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "InetAddr.hpp"
#include "nocopy.hpp"
#include "log.hpp"
using namespace log_ns;

static int gsockfd = -1;
static int localport = 8888;

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR = 2
};

using service_t = std::function<void(int, const std::string, InetAddr&)>;

class Udpserver : public nocopy
{
public:
    Udpserver(service_t func, uint16_t port = localport)
        : _func(func), _localport(port), _sockfd(gsockfd)
    {
    }
    void Init()
    {
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error!\n");
            exit(SOCK_ERROR);
        }
        LOG(DEBUG, "create socket success, _sockfd: %d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport); // 将主机序列转换成网络序列
        local.sin_addr.s_addr = INADDR_ANY; // 服务器端进行任意地址绑定

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error!\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success!\n");
    }

    void Start()
    {
        _isrunning = true;
        char message[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                message[n] = 0;

                LOG(DEBUG,"[%s]# %s\n",addr.AddrStr().c_str(),message);

                _func(_sockfd,message,addr); 
                LOG(DEBUG,"return udpserver\n");
            }
            else
            {
                std::cout<<"recvfrm error!"<<std::endl;
            }
        }
        _isrunning = false;
    }

    ~Udpserver()
    {
        if (_sockfd > gsockfd)
            close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _localport;

    bool _isrunning;

    service_t _func;
};